package com.itheima.reggie.filter;

import com.alibaba.fastjson.JSON;
import com.itheima.reggie.common.BaseContext;
import com.itheima.reggie.common.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.AntPathMatcher;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

//完善登录，过滤器
@WebFilter(filterName = "loginCheckFilter",urlPatterns = "/*")
@Slf4j
public class LoginCheckFilter implements Filter {
    //路径匹配器，支持通配符
    public static final AntPathMatcher PATH_MATCHER = new AntPathMatcher();

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        HttpServletRequest request1 = (HttpServletRequest) request;
        HttpServletResponse response1 = (HttpServletResponse) response;

        //1.获取本次请求的uri
        String requestURI = request1.getRequestURI();
        log.info("拦截到请求：{}",requestURI);

        //定义不需要处理的请求路径
        String[] urls=new String[]{
                "/employee/login",
                "/employee/logout",
                "/backend/**",
                "/front/**",
                "/common/**",
                "/user/sendMsg",
                "/user/login"
        };

        //2.判断本次请求是否需要处理
        boolean check = check(urls, requestURI);
        //3.如果不需要处理，则直接放行
        if(check){
            //放行
            log.info("本次请求不需要处理：{}",requestURI);
            chain.doFilter(request1,response1);
            return;
        }

        //4.判断登录状态，如果已经登录，则直接放行
        Object employee =  request1.getSession().getAttribute("employee");
        if(employee!=null){
            log.info("用户已登录，用户id为:{}",employee);
            //将当前登录用户的id保存到ThreaLocal副本
            BaseContext.setCurrentId((Long) employee);
            //放行
            chain.doFilter(request1,response1);
            return;
        }

        //5.判断登录状态，如果已经登录，则直接放行
        Object user =  request1.getSession().getAttribute("user");
        if(user!=null){
            log.info("用户已登录，用户id为:{}",user);
            //将当前登录用户的id保存到ThreaLocal副本
            BaseContext.setCurrentId((Long) user);
            //放行
            chain.doFilter(request1,response1);
            return;
        }

        log.info("用户未登录！");
        //5.如果没有登录，则响应code和msg给前端作页面跳转（通过输出流向客户端页面响应数据）
        response1.getWriter().write(JSON.toJSONString(R.error("NOTLOGIN")));
    }

    /**
     * 路径匹配，判断本次请求是否需要放行
     * @param urls 路径数组
     * @param requestURI
     * @return
     */
    public boolean check(String[] urls,String requestURI){
    for(String url:urls){
        if(PATH_MATCHER.match(url,requestURI)){
            return true;
        }
    }
        return false;
    }

}
